import csv
import time

from pyecharts.charts import Pie, Line, Page
from pyecharts import options as opts


def draw_pie(tags_play_volume, name):
    v1 = [list(z) for z in zip(tags_play_volume.keys(), tags_play_volume.values())]
    v1 = sorted(v1, key=lambda x: x[1], reverse=True)
    if len(v1) > 10:
        v1 = v1[0:10]
    pie = (
        Pie().add("",
                  v1[0:10],
                  radius=["30%", "75%"],
                  center=["35%", "60%"],
                  rosetype="radius",
                  )
            .set_global_opts(title_opts=opts.TitleOpts(title=name + "近期视频中播放量最高的10个标签"),
                             legend_opts=opts.LegendOpts(pos_top="5%"))
    )
    return pie


def draw_line(times, play_volume, name, average):
    line = (
        Line()
            .add_xaxis(xaxis_data=times)
            .add_yaxis("相关标签的播放量", y_axis=play_volume)
            .add_yaxis("近期视频的平均播放量", y_axis=[average] * len(times),
                       label_opts=opts.LabelOpts(is_show=False))
            .set_global_opts(title_opts=opts.TitleOpts(title=name + "近期视频中相关标签的播放量"),
                             legend_opts=opts.LegendOpts(pos_top="5%"))
    )
    return line


def draw_pie_line(key_tag, ups):
    # 将up主的id放入ups_all中，将up主的视频播放量、时间和标签放入info中
    # ups_all = []
    info = dict()
    up_name = dict()
    with open("data.csv", encoding="utf-8", mode='r') as f:
        reader = csv.DictReader(f)
        for row in reader:
            info[row['video_up_mid']] = []
            # if row['video_up_mid'] not in ups_all:
            #     ups_all.append(row['video_up_mid'])
    with open("data.csv", encoding="utf-8", mode='r') as f:
        reader = csv.DictReader(f)
        for row in reader:
            info[row['video_up_mid']].append([int(row['video_play']), int(row['video_created']), row['video_tags']])
    # print(info)
    # 读取up的名字
    with open("up.csv", encoding="utf-8", mode='r') as f:
        reader = csv.DictReader(f)
        for row in reader:
            up_name[row['mid']] = row['up_name']

    # 数据处理与绘图
    images = []
    for up in ups:
        if up not in up_name.keys():
            continue
        tags_play_volume = dict()
        key_tag_time = []
        key_tag_play_volume = []
        time_flag = set()
        play_sum = 0
        play_amt = 0
        for video in info[up]:
            play_sum += video[0]
            play_amt += 1
            tags = video[2][1:-2].split(", ")
            for tag in tags:
                if tag not in tags_play_volume:
                    tags_play_volume[tag] = video[0]
                else:
                    tags_play_volume[tag] += video[0]
                if tag.__contains__(key_tag) and video[1] not in time_flag:
                    time_flag.add(video[1])
                    key_tag_time.append(video[1])
                    key_tag_play_volume.append(video[0])
        key_tag_time = sorted(key_tag_time)
        times = [time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(x)) for x in key_tag_time]
        name = "[" + up_name[up] + "]"
        images.append(draw_pie(tags_play_volume, name))
        avg = int(play_sum / play_amt)
        images.append(draw_line(times, key_tag_play_volume, name, avg))
    return images
